import os
import cv2
from werkzeug.utils import secure_filename
from datetime import datetime
import hashlib
import shutil
from moviepy.video.io.VideoFileClip import VideoFileClip
import uuid
from PIL import Image
import numpy as np
import imagehash
import ujson  # 高性能JSON库，需pip安装
import mmap

def find_files(directory, extensions=('.mp4', '.avi', '.mov')):
    """
    递归查找目录下所有指定扩展名的视频文件
    :param directory: 要搜索的根目录路径
    :param extensions: 包含目标扩展名的元组
    :return: 匹配文件的完整路径列表
    """
    output_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(extensions):
                output_files.append(os.path.join(root, file))
    return output_files

def get_partial_md5(file_path, chunk_size=1000):
    md5 = hashlib.md5()
    with open(file_path, 'rb') as f:
        data = f.read(chunk_size)  # 读取最多1000字节
        md5.update(data)
    return md5.hexdigest()

def fast_json_write(data, filepath):
    """高性能JSON写入"""
    with open(filepath, 'w', encoding='utf-8') as f:
        # ujson比标准json库快4-10倍
        ujson.dump(data, f, ensure_ascii=False)

def fast_json_read(filepath):
    """高性能JSON读取"""
    if not os.access(filepath, os.F_OK):
        return {}
    with open(filepath, 'r+', encoding='utf-8') as f:
        # 使用内存映射加速大文件读取
        mm = mmap.mmap(f.fileno(), 0)
        try:
            return ujson.load(mm)
        finally:
            mm.close()

def safe_json_write(data, filepath):
    """原子性写入（避免写入过程中断导致文件损坏）"""
    tmp_path = f"{filepath}.tmp"
    fast_json_write(data, tmp_path)
    os.replace(tmp_path, filepath)